#!/usr/bin/env python3
"""
测试Qwen3-VL超时问题的解决方案
"""
import requests
import json
import time
import asyncio
import httpx

async def test_with_different_timeouts():
    """测试不同超时时间"""
    
    api_url = "http://192.168.200.19:18009/api/generate"
    video_url = "http://192.168.210.72:8000/videos/502be57a-11fa-465a-8708-b993125d399e.mp4"
    
    # 测试不同的超时时间
    timeouts = [30, 60, 120, 300]  # 30秒, 1分钟, 2分钟, 5分钟
    
    request_data = {
        "prompt": "简单描述视频",  # 使用更简单的提示词
        "model": "Qwen3-VL",
        "videos": [video_url],
        "stream": False
    }
    
    headers = {
        "Content-Type": "application/json",
        "Accept": "*/*",
        "Connection": "keep-alive"
    }
    
    print("🔍 测试不同超时时间...")
    
    for timeout in timeouts:
        print(f"\n⏱️ 测试超时时间: {timeout}秒")
        
        try:
            start_time = time.time()
            
            async with httpx.AsyncClient(timeout=timeout) as client:
                response = await client.post(
                    api_url,
                    json=request_data,
                    headers=headers
                )
            
            end_time = time.time()
            actual_time = end_time - start_time
            
            print(f"✅ 成功! 实际耗时: {actual_time:.2f}秒")
            print(f"📊 状态码: {response.status_code}")
            
            if response.status_code == 200:
                try:
                    result = response.json()
                    print(f"📄 响应类型: {type(result)}")
                    if isinstance(result, dict):
                        print(f"📋 响应字段: {list(result.keys())}")
                    print(f"📝 响应内容: {str(result)[:200]}...")
                except:
                    print(f"📝 文本响应: {response.text[:200]}...")
            else:
                print(f"❌ 错误: {response.text[:200]}...")
            
            # 如果成功了，就不需要测试更长的超时时间
            break
            
        except asyncio.TimeoutError:
            print(f"❌ 超时 ({timeout}秒)")
            continue
        except Exception as e:
            print(f"❌ 错误: {e}")
            continue
    
    print("\n💡 建议:")
    print("1. 如果所有超时时间都失败，可能是视频文件太大")
    print("2. 尝试使用更小的视频文件（<1MB）")
    print("3. 检查Qwen3-VL服务的配置和性能")

async def test_video_info():
    """获取视频信息"""
    video_url = "http://192.168.210.72:8000/videos/502be57a-11fa-465a-8708-b993125d399e.mp4"
    
    print("📹 获取视频信息...")
    
    try:
        async with httpx.AsyncClient(timeout=10) as client:
            response = await client.head(video_url)
            
            if response.status_code == 200:
                content_length = response.headers.get('content-length')
                content_type = response.headers.get('content-type')
                
                if content_length:
                    size_mb = int(content_length) / (1024 * 1024)
                    print(f"📊 视频大小: {size_mb:.2f} MB")
                    print(f"📋 内容类型: {content_type}")
                    
                    if size_mb > 10:
                        print("⚠️ 警告: 视频文件较大，可能导致处理超时")
                    if size_mb > 50:
                        print("❌ 错误: 视频文件过大，建议使用更小的文件")
                else:
                    print("❓ 无法获取视频大小信息")
            else:
                print(f"❌ 无法访问视频: {response.status_code}")
                
    except Exception as e:
        print(f"❌ 获取视频信息失败: {e}")

async def main():
    print("=" * 60)
    print("Qwen3-VL 超时问题诊断工具")
    print("=" * 60)
    
    await test_video_info()
    print("\n" + "-" * 60)
    await test_with_different_timeouts()
    
    print("\n" + "=" * 60)
    print("诊断完成")
    print("=" * 60)

if __name__ == "__main__":
    asyncio.run(main())